package xyz.hubery.task;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import xyz.hubery.dto.MarketDto;
import xyz.hubery.event.KlineEvent;
import xyz.hubery.feign.MarketServiceFeign;
import xyz.hubery.stream.Source;

import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * K 线数据的推送
 */
@Component
@Slf4j
public class TopicKLineTask {
    private ExecutorService executor = null;

    {
        executor = new ThreadPoolExecutor(
                5,
                10,
                100L, TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<>(30),
                new ThreadPoolExecutor.CallerRunsPolicy());
    }

    @Autowired
    private MarketServiceFeign marketServiceFeign;
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;
    @Autowired
    private Source source;

    /**
     * 每 30 秒推送 K 线数据
     */
    @Scheduled(fixedRate = 30000)
    public void pushKline() {
        // 获取所有的市场
        List<MarketDto> markets = marketServiceFeign.findAllMarkets();
        if(!CollectionUtils.isEmpty(markets)) {
            for (MarketDto market : markets) {
                executor.submit(new KlineEvent(market.getSymbol(),redisTemplate,source));
            }
        }
    }

}